package com.apidoc.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import com.apidoc.config.ApiDocProperties;
import com.apidoc.core.ApiDocGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.apidoc.model.ApiDocInfo;
import com.apidoc.model.ControllerInfo;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

@Controller
@RequestMapping("/api-docs")
public class ApiDocController {
    @Autowired
    private ApiDocGenerator apiDocGenerator;

    @Autowired
    private ApiDocProperties apiDocProperties;

    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 使用Thymeleaf动态渲染接口文档HTML
     */
    @GetMapping(produces = "text/html;charset=UTF-8")
    public String getApiDocHtml(Model model) {
        try {
            // 1. 生成API文档数据
            apiDocGenerator.generate();

            // 2. 读取生成的JSON数据文件
            File jsonFile = new File(apiDocProperties.getOutputPath(), "api-docs.json");
            if (!jsonFile.exists()) {
                model.addAttribute("error", "API文档数据不存在，请检查生成配置");
                return "api-docs-error"; // 错误页面模板
            }

            // 3. 解析JSON数据为Java对象（使用新的ApiDocInfo模型）
            ApiDocInfo apiDocInfo = objectMapper.readValue(
                    Files.readAllBytes(Paths.get(jsonFile.getAbsolutePath())),
                    ApiDocInfo.class
            );

            // 4. 计算总接口数量
            int totalApis = 0;
            if (apiDocInfo.getControllers() != null) {
                for (ControllerInfo controller : apiDocInfo.getControllers()) {
                    if (controller.getApis() != null) {
                        totalApis += controller.getApis().size();
                    }
                }
            }

            // 5. 将数据添加到模型，供Thymeleaf模板使用
            model.addAttribute("totalApis", totalApis);
            model.addAttribute("controllers", apiDocInfo.getControllers());
            model.addAttribute("generatedTime", new java.util.Date());

            // 6. 返回Thymeleaf模板名称
            return "api-docs";

        } catch (Exception e) {
            model.addAttribute("error", "文档渲染失败: " + e.getMessage());
            return "api-docs-error";
        }
    }

    /**
     * 访问 JSON 数据（用于调试，确认数据是否正确）
     */
    @GetMapping(value = "/json", produces = "application/json;charset=UTF-8")
    public ResponseEntity<Resource> getApiDocJson() {
        // 保持原有实现不变
        apiDocGenerator.generate();
        File jsonFile = new File(apiDocProperties.getOutputPath(), "api-docs.json");
        if (!jsonFile.exists()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Resource resource = new FileSystemResource(jsonFile);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")
                .body(resource);
    }
}